package com.epfresh.supplier.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.dialog.AreaDialog;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.City;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.supplier.entity.Flag;
import com.epfresh.supplier.entity.PickUpAddressesEntity;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class NewPickupAddressActivity extends BaseActivity {

    static final String TAG = "NewPickupAddressActivity";

    private TextView areaTv;
    private EditText detailEt;
    Button sureBu;
    EditText nameEt;
    private EditText phoneEt;
    private EditText addressNameEt;
    String provinceId = "";
    String cityId = "";
    String districtId = "";
    String provinceName = "";
    String cityName = "";
    String districtName = "";
    String id = "";

    String accountId = "";
    String address = "";
    String contactName;
    String post_code;
    String phone;
    String name;
    private String cityname;
    private boolean isEdit;

    //private String cityname, cityid,areaid,provinceid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText("添加提货地址");
        setContentView(R.layout.activity_newaddress);
        areaTv = (TextView) findViewById(R.id.area);
        areaTv.setOnClickListener(this);
        detailEt = (EditText) findViewById(R.id.detail);
        sureBu = (Button) findViewById(R.id.sure);
        sureBu.setOnClickListener(this);
        phoneEt = (EditText) findViewById(R.id.phone);
        nameEt = (EditText) findViewById(R.id.name);
        addressNameEt = (EditText) findViewById(R.id.address_name);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        if (id != null) {
            isEdit = true;
            provinceId = intent.getStringExtra("provinceId");
            cityId = intent.getStringExtra("cityId");
            districtId = intent.getStringExtra("districtId");
            cityId = intent.getStringExtra("cityId");
            provinceName = intent.getStringExtra("provinceName");
            cityName = intent.getStringExtra("cityName");
            districtName = intent.getStringExtra("districtName");
            accountId = intent.getStringExtra("accountId");
            address = intent.getStringExtra("address");
            name = intent.getStringExtra("name");
            phone = intent.getStringExtra("phone");
            contactName = intent.getStringExtra("contactName");
            nameEt.setText(contactName);
            addressNameEt.setText(name);
            if (name != null)
                addressNameEt.setSelection(name.length());
            phoneEt.setText(phone);
            toolbarTitle.setText("编辑地址");
            areaTv.setText(provinceName + cityName + districtName);
            detailEt.setText(address);
        }
/*        rightbtn.setText("保存");
        rightbtn.setVisibility(View.VISIBLE);*/
        phoneEt.addTextChangedListener(new TextWatcher() {
            int beforeLen = 0;
            int afterLen = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeLen = s.length();
                phoneEt.setSelection(beforeLen);

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                afterLen = s.length();
            }

            @Override
            public void afterTextChanged(Editable s) {

                String tel = s.toString();
                //手机号
                if (tel.startsWith("1")) {
                    if (tel.length() > 11) {
                        s.delete(11, 12);
                    }
                } else if (tel.startsWith("0") && beforeLen < afterLen) {
                    if (tel.startsWith("01")) {
                        if (tel.length() == 2) {
                            tel = "010-";
                            s.insert(2, "0-");
                        }
                    } else if (tel.startsWith("02")) {
                        if (tel.length() == 3) {
                            s.insert(3, "-");
                        }
                    } else if (tel.length() == 4) {
                        s.insert(4, "-");
                    }

                } else if (tel.startsWith("0") && beforeLen > afterLen) {

                } else if (tel.startsWith("86")) {
                    s.delete(0, 2);
                } else if (tel.startsWith("+86")) {
                    s.delete(0, 3);
                } else {
                    s.clear();
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.area:
//                Intent edit = new Intent(getApplicationContext(),
//                        MainActivity.class);
//                edit.putExtra("provinceId", provinceId);
//                edit.putExtra("cityId", cityId);
//                edit.putExtra("districtId", districtId);
//                edit.putExtra("provinceName", provinceName);
//                edit.putExtra("cityName", cityName);
//                edit.putExtra("districtName", districtName);
//                startActivityForResult(edit, 1);
                openArea();
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.sure:
            case R.id.rightbtn:
                postSave();
                break;
        }
    }


    City cityData;

    public void openArea() {
        AreaDialog areaDialog = new AreaDialog(this);
        if (cityData == null)
            cityData = areaDialog.getCityData();
        areaDialog.setPositiveDismiss(true);
        areaDialog.setCurrentIndex(cityData, provinceId, cityId, districtId);
        ;
        areaDialog.setOnPositiveClickListener(new AreaDialog.OnPositiveClickListener() {

            @Override
            public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3) {
//                if (city1 != null && city2 != null && city3 != null) {
//                    cityName = city1.getName() + city2.getName() + city3.getName();
//                    provinceId = city1.getCode();
//                    cityId = city2.getCode();
//                    districtId = city3.getCode();
//                    areaTv.setText(cityName);
//                }

                if (city1 != null) {
                    cityName = city1.getName();
                    provinceId = city1.getCode();
                }
                if (city1 != null && city2 != null) {
                    cityName = city1.getName() + city2.getName();
                    cityId = city2.getCode();
                }
                if (city1 != null && city2 != null && city3 != null) {
                    cityName = city1.getName() + city2.getName() + city3.getName();
                    districtId = city3.getCode();
                }
                areaTv.setText(cityName);
            }
        });
        areaDialog.show();
    }


    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent date) {
        super.onActivityResult(requestcode, resultcode, date);
        switch (resultcode) {
            case 1:
                // 回传城市名字 城市ID
                if (date != null) {
                    cityname = date.getExtras().getString("name");
                    provinceId = date.getStringExtra("provinceCode");
                    cityId = date.getStringExtra("cityCode");
                    districtId = date.getStringExtra("areaCode");
                    provinceName = date.getStringExtra("provinceName");
                    cityName = date.getStringExtra("cityName");
                    districtName = date.getStringExtra("areaName");
                    areaTv.setText(cityname);
                    Log.i("just 测试", date.getStringExtra("provinceCode") + "," + date.getStringExtra("cityCode") + "," + date.getStringExtra("areaCode"));
                }
                break;
        }
    }


    void postSave() {

        if (InputControl.isEmpty(addressNameEt)) {
            ToastUtils.TextToast(this, "请填写提货点名称");
            return;
        }
        if (!VerificationUtils.isValid(addressNameEt.getText().toString())) {
            toast(getString(R.string.illegal_input, "提货点名称"));
            return;
        }
        if (InputControl.isEmpty(areaTv)) {
            ToastUtils.TextToast(this, "请先选择区域");
            return;
        }
        if (InputControl.isEmpty(detailEt)) {
            ToastUtils.TextToast(this, "请先填写详细地址");
            return;
        }
        if (!VerificationUtils.isValid(detailEt.getText().toString())) {
            toast(getString(R.string.illegal_input, "详细地址"));
            return;
        }
        if (InputControl.isEmpty(nameEt)) {
            ToastUtils.TextToast(this, "请填写联系人姓名");
            return;
        }
        if (!VerificationUtils.isValid(nameEt.getText().toString())) {
            toast(getString(R.string.illegal_input, "联系人姓名"));
            return;
        }
        if (InputControl.isEmpty(phoneEt)) {
            ToastUtils.TextToast(this, "请填写联系电话");
            return;
        }
        if (phoneEt.getText().toString().length() != 11) {
            toast("请填写正确的手机号");
            return;
        } else if (!VerificationUtils.isTelPhone(phoneEt.getText().toString())) {
            toast("请填写正确的联系电话");
            return;
        }
        PickUpAddressesEntity pickUpAddressesEntity = new PickUpAddressesEntity();
        if (!TextUtils.isEmpty(id)) {
            pickUpAddressesEntity.setUuid(id);
        } else {
            pickUpAddressesEntity.setUuid(UUID.randomUUID().toString());
        }
        pickUpAddressesEntity.setAddress(detailEt.getText().toString());
        pickUpAddressesEntity.setCityId(cityId);
        pickUpAddressesEntity.setDistrictId(districtId);
        pickUpAddressesEntity.setProvinceId(provinceId);
        pickUpAddressesEntity.setProvinceName(provinceName);
        pickUpAddressesEntity.setCityName(cityName);
        pickUpAddressesEntity.setDistrictName(districtName);
        pickUpAddressesEntity.setTel(phoneEt.getText().toString());
        pickUpAddressesEntity.setContactName(nameEt.getText().toString());
        pickUpAddressesEntity.setName(addressNameEt.getText().toString());


        SharedPreferences sp = FileUtil.getSharedPreferences();
        String str = sp.getString(Constant.KEY_PICK_UP_ADDRESS + "_" + getUser().getAccountId(), "");
        List<PickUpAddressesEntity> list = new ArrayList<>();
        if (!TextUtils.isEmpty(str)) {
            list = new Gson().fromJson(str, new TypeToken<List<PickUpAddressesEntity>>() {
            }.getType());

            if (list == null || list.size() < 1) {
                //没有本地地址存储


            } else {

            }
        }
        if (isEdit) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != null && list.get(i).getUuid() != null && list.get(i).getUuid().equals(id)) {
                    list.remove(i);
                }
            }
        } else {
        }
        list.add(0, pickUpAddressesEntity);


        L.d("city", new Gson().toJson(list) + "");
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(Constant.KEY_PICK_UP_ADDRESS + "_" + getUser().getAccountId(), new Gson().toJson(list));
        edit.commit();
        setResult(RESULT_OK);
        finish();
    }


    OnRequestListener<Flag> onRequestListener = new OnRequestListener<Flag>() {
        @Override
        public Flag jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, Flag.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<Flag> response, Object tag) {
            Flag flag = response.getResponseElement();
            if (flag.isSuccess() == true) {
                if (!isEdit)
                    getUser().addDeliveryAddressCount();
                toast(BaseApplication.getDoc().getBeenSubmitted());
                finish();
            } else {

            }
        }
    };


}
